<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/4/19
 * Time: 14:41
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\api\controller\v1;

use app\admin\controller\mall\SpecsValue;
use app\common\business\BusGoods;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\MallCollect;
use app\common\model\MallGoods;
use app\common\model\MallGoodsSku;
use app\common\model\MallSearchUser;
use app\common\model\MallShop;
use app\common\model\MallSpecsValue;
use think\App;
use think\facade\Log;

class Goods extends Base
{
    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallGoods();
    }

    public function goodsIndexList()
    {
        if (!$this->request->isPost()) {
            return Show::json_show(Status::mini_error, "请求类型异常");
        }
        $cate_ids = $this->request->param('cate_ids', []);
        if (empty($cate_ids)) {
            return Show::json_show(Status::mini_error, "分类异常");
        }
        $num = $this->request->param('num', 10, 'intval');
        //查询分类
        try {
            $lists = $this->model->goodsIndexList($cate_ids, $num, 'id,price,title,thumb_title,logo');
        } catch (\Exception $exception) {
            return Show::json_show(Status::mini_error, "查询失败");
        }
        return Show::json_show(Status::mini_normal, 'ok', $lists);
    }

    /**
     * 搜索商品
     * @return \think\response\Json
     */
    public function getGoodsList()
    {
        $keyword = $this->request->param('keyword', '', 'trim');
        $page = $this->request->param('page', 1, 'intval');
        $where = [];
        if ($keyword) {
            $where[] = [['title', 'like', '%' . $keyword . '%']];
        }
        $where[] = [['status', '=', 1]];
        try {
            $lists = $this->model->field('id,title,logo,price')->where($where)->page($page, 10)->select()->toArray();
        } catch (\Exception $e) {
            Log::error("goods_getTopTenByListInfo" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        return Show::json_show(Status::mini_normal, "ok", [
            'goods' => $lists ?? []
        ]);
    }

    /**
     * 按照销量排序
     * @return \think\response\Json
     */
    public function getTopTenByListInfo()
    {
        try {
            $lists = $this->model->getTopTenByList();
        } catch (\Exception $e) {
            Log::error("goods_getTopTenByListInfo" . $e->getMessage() . " " . $e->getFile() . "　" . $e->getLine());
            return Show::json_show(Status::mini_error, "查询错误");
        }
        return Show::json_show(Status::mini_normal, "ok", $lists);
    }

    /**
     * 商品详情
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function getGoodsDetail()
    {
        $goods_id = $this->request->param('id', 0, 'intval');  //sku_id
        //
        $goodsSkuObj = new MallGoodsSku();
        $goodsSku = $goodsSkuObj->getGoodsByDetail($goods_id);

        if (empty($goodsSku)) {
            return Show::json_show(Status::mini_error, "商品信息不存在");
        }
        if (empty($goodsSku['goods'])) {
            return Show::json_show(Status::mini_error, '商品信息不存在');
        }
        $goods = $goodsSku['goods'];
        if ($goods['status'] != 1) {
            return Show::json_show(Status::mini_error, "商品已经下架");
        }
        try {
            $sku = $goodsSkuObj->getSkuByGoodsId($goods['id']);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "内部错误");
        }
        $flagValue = '';
        foreach ($sku as $v) {
            if ($v['id'] == $goods_id) {
                $flagValue = $v['specs_value_ids'];
            }
        }
        $gids = array_column($sku, 'id', 'specs_value_ids');
        if (!empty($goods['describe'])) {
            $goods['describe'] = htmlspecialchars_decode($goods['describe']);
        }
        if (!empty($goods['images'])) {
            $goodsImage = explode('|', $goods['images']);

            $images = [];
            foreach ($goodsImage as $v) {
                $images[] = [
                    "url" => $v
                ];
            }
            $goods['images'] = $images;
        }
        if ($goods['specifications'] == 0) {
            $skus = [];
        } else {
            $skus = (new MallSpecsValue())->getDetailByGoodsSku($gids, $flagValue);
        }

        //获取是否收藏商品
        try {
            $collect = (new MallCollect())->getMallCollectByOpenidAndGoodsInfo($this->m_openid, $goods['id']);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "内部错误");
        }

        $result = [
            "title" => $goods['title'],
            "price" => $goodsSku['price'],
            "market_price" => $goodsSku['market_price'],
            "stock" => $goodsSku['stock'],
            "sale_count" => $goodsSku['sale_count'],
            "gids" => $gids,
            "images" => $goods['images'],
            "sku" => $skus,
            "detail" => [
                "d1" => [],
                "d2" => $goods['describe']
            ],
            "source"=>$goods['source'],
            "collect" => $collect ? 1 : 0,
            "thumb_title" => $goods['thumb_title'],
            "id" => $goods['id'],
            "sku_id" => $goodsSku['id'],
            "specifications" => $goods['specifications'],
            "sku_img" => $goodsSku['image'],
        ];

        return Show::json_show(Status::mini_normal, "ok", $result);
    }

    /**
     * 收藏 商品
     * @return array|\think\response\Json
     */
    public function doGoodsCollect()
    {
        $goods_id = $this->request->param('goods_id', 0, 'intval');
        if ($goods_id == 0) {
            return Show::json_show(Status::mini_error, "内部异常");
        }
        //查询是否收藏 如果收藏则取消 如果没有收藏 则收藏
        $obj = new MallCollect();
        try {
            $collect = $obj->getMallCollectByOpenidAndGoodsInfo($this->m_openid, $goods_id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "查询错误");
        }
        if ($collect) {
            $res = $obj->where('id', $collect['id'])->delete();
            $name = "取消收藏";
        } else {
            $insert_data = [
                "openid" => $this->m_openid,
                "goods_id" => $goods_id
            ];
            $res = $obj->insertSaveById($insert_data);
            $name = "收藏成功";
        }
        if ($res) {
            return Show::json_show(Status::mini_normal, $name);
        } else {
            return Show::json_show(Status::mini_error, "操作失败");
        }
    }

    public function getSearchByListInfo()
    {
        $keywords = $this->request->param('keywords', '', 'trim');
        $page = $this->request->param('page', 1, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        if (empty($keywords)) {
            return Show::json_show(Status::mini_error, "请输入关键词");
        }
        if (preg_match('/<(\w+)[^>]*>(.*?<\/\1>)?/', $keywords)) {
            return Show::json_show(Status::mini_error, "搜索非法");
        }
        //增加用户搜索记录
        $obj = new MallSearchUser();
        $g_data = [
            "keywords" => $keywords,
            "openid" => $this->m_openid,
        ];
        $res = $obj->insertSaveById($g_data);

        if ($res) {
            //搜索页面
            $where[] = [
                ['shop_id', '=', $this->shop_id],
                ["title", 'like', "%{$keywords}%"],
                ['status', '=', 1]
            ];
            try {
                $lists = $this->model->getPaginateByNormalListInfo($where, $limit, 'id,sku_id,title,thumb_title,price,market_price,logo', 'sort desc,id desc');
            } catch (\Exception $e) {
                return Show::json_show(Status::mini_error, $e->getMessage());
            }
            return Show::json_show(Status::mini_normal, "ok", $lists['data'], $lists['total'], false, $lists['last_page']);
        } else {
            return Show::json_show(Status::mini_error, "内部错误");
        }
    }

    /**
     * 获取随机商品
     * @return array|\think\response\Json
     * @throws \think\Exception
     */
    public function getRandomGoods()
    {
        if ($this->shop_id == 0) {
            return Show::json_show(Status::mini_error, "请选择驿点");
        }
        $lists = (new BusGoods())->getRandomGoods(10, $this->shop_id);
        return Show::json_show(Status::mini_normal, "ok", $lists);
    }
}